// pages/ShopCart/ShopCart.js
const Controller = require('../controllers/controllers.js').controller;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        result: [],
        scorllY:true,
        transY:0,
        copyResult: [],

        allResult: [],
        list: [],
        goodList: [],
        price: 0,
        oldAmount: 0,

        page:0,
        pageSize:10,
        lastPage:false

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // this.getList()
    },
    change(e) {
        let result = e.detail

        let allResult = ['1']

        for (let item of this.data.copyResult) {
            if (!result.includes(item)) {
                allResult = []
            }
        }
        this.setData({
            result,
            allResult
        });
        this.getPrice()

    },
    //再次购买
    buy(e) {
        wx.switchTab({
            url: '/pages/Types/Types'
        })
    },
    //删除购物车
    delItem(e) {
        let index = e.currentTarget.dataset.index
        let list = this.data.list
        let that = this
        let price=0
        wx.showModal({
            title: '提示',
            content: '是否删除购物车?',
            success(res) {
                if (res.confirm) {
                    Controller.deleteCart({
                        cartIds: list[index].cartId
                    }).then(res => {
                        wx.showToast({
                            title: '删除成功',
                        })
                        list.splice(index, 1)

                    
              
                        that.setData({
                            list
                        },()=>{
                            that.getPrice()
                        })
                    })
                }
            }
        })
    },
    //获取商品列表
    getList() {
       
        Controller.goodslist({
            isRecommend: 1,
            page:1
        }).then(res => {
            let baseData = res.data.baseData
            this.setData({
                goodList: baseData.list,
            })
        })
    },
    //跳转详情
    goDetail(e) {
        let id = e.currentTarget.dataset.id
        wx.navigateTo({
            url: `/pages/Detail/detail?id=${id}`,
        })
    },
    //获取购物车
    getCartList() {
      let page=this.data.page
      let pageSize=this.data.pageSize
        Controller.cartlist().then(res => {
            let list = res.data.baseData
            let copyResult = []
            list.forEach(item => {
                copyResult.push(String(item.cartId))
                item.specsList = item.specs.split(',')
                item.discountPrice=item.discountPrice?item.discountPrice:0.00
            })



           
            
            this.setData({
                list,
                copyResult
            },()=>{
                this.getPrice()
            })
        })
    },
    changeAllSelect(e) {
        let result = []
        if (e.detail.length > 0) {
            result = this.data.copyResult
        }
        this.setData({
            allResult: e.detail,
            result
        })
        this.getPrice()

    },
    onChange(e) {
      
        this.setData({
            radio: this.data.radio == '0' ? '1' : '0'
        })
    },
    //减
    minus(e) {
        e=e.detail
        let index = e.currentTarget.dataset.index
        let list = this.data.list
        this.joinCart(list[index].goodsId, list[index].specs, list[index].attrIds, 1, list[index].goodsSpecAttributePriceId, 2, list[index].stock < list[index].amount)
        this.getPrice()
    },
    //加
    plus(e) {
     
        e=e.detail
       
        let index = e.currentTarget.dataset.index
        let list = this.data.list
        this.joinCart(list[index].goodsId, list[index].specs, list[index].attrIds, 1, list[index].goodsSpecAttributePriceId, 1, list[index].stock < list[index].amount)
       
    },
    //输入框对焦
    focus(e) {
   
        e=e.detail
       
        let index = e.currentTarget.dataset.index
        let list = this.data.list
        this.setData({
            oldAmount: list[index].amount
        })
    },
    //输入框失去对焦
    blur(e) {
     
        e=e.detail
    
        let index = e.currentTarget.dataset.index
        let list = this.data.list
        let type = 1
        let amount = 1
        if (e.detail.value < this.data.oldAmount) {
            type = 2
            amount = this.data.oldAmount - e.detail.value
        } else {
            amount = e.detail.value - this.data.oldAmount
        }
        let callBack=()=>{
          this.data.list[index].amount=this.data.oldAmount
            this.setData({
              list:this.data.list
            })
        }

        amount=amount<1?1:amount
        this.joinCart(list[index].goodsId, list[index].specs, list[index].attrIds, amount, list[index].goodsSpecAttributePriceId, type, list[index].stock < e.detail.value,callBack)

    },
    //加入购物车
    joinCart(goodsId, specs, attrIds, amount, goodsSpecAttributePriceId, type, stock,callBack) {
       
        if (stock) {
            wx.showToast({
                title: '暂无库存',
                icon: 'none'
            })
            callBack()
            return
        }
        Controller.addOrUpdate({
            goodsId,
            specs,
            attrIds,
            amount,
            goodsSpecAttributePriceId,
            type,
        }).then(res => {
            this.getCartList()
        }).catch(err=>{
            this.getCartList()
        })

    },
    //结算
    submit() {  
        let cartIds = []   

        console.log('this.data.result',this.data.result)

        for(let v of this.data.list){
            
         if(this.data.result.includes(String(v.cartId))&&v.amount>0){
            cartIds.push(v.cartId)
         }
        }
      

            

         
        
        
        if (cartIds.length == 0) {
            wx.showToast({
                title:'选择不能为空',
                icon: 'none'
            })
            return
        }
        cartIds = cartIds.join(',')
        wx.navigateTo({
            url: `/pages/Pay/pay?cartIds=${cartIds}&type=cart`
        })
    },
    //获取总价格
    getPrice() {
        let result = this.data.result
        let list = this.data.list
        let price = 0
        let select = list.filter(item => result.indexOf(String(item.cartId)) != -1)

        select.forEach(item => {
            price += (Number(item.discountPrice) * 100 * item.amount)
        })
        this.setData({
            price
        })
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {
        this.setData({
            result: [],
            copyResult: [],
            allResult: [],
            goodList: [],
            price: 0,
            oldAmount: 0,
            page:1,
            pageSize:10,
            lastPage:false
            
        })
        // this.getList()
        this.getCartList()
       
        
    },
    ScrollToBottom(){
    // console.log('ScrollToBottom==>')
    //    if(this.data.lastPage){
    //       return wx.showToast({
    //          title: '没有更多商品了',
    //          icon:"none"
    //        })
    //    }else{
    //          this.data.page+=1
    //          this.getList()
    //    }
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})